/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Controllers;

import Controllers.exceptions.IllegalOrphanException;
import Controllers.exceptions.NonexistentEntityException;
import Entities.Owner;
import java.io.Serializable;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import Entities.Person;
import Entities.Pet;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;

/**
 *
 * @author Heinz Hernandez
 */
public class OwnerJpaController implements Serializable {

    public OwnerJpaController(EntityManagerFactory emf) {
        this.emf = emf;
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Owner owner) {
        if (owner.getPetList() == null) {
            owner.setPetList(new ArrayList<Pet>());
        }
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Person perId = owner.getPerId();
            if (perId != null) {
                perId = em.getReference(perId.getClass(), perId.getPerId());
                owner.setPerId(perId);
            }
            List<Pet> attachedPetList = new ArrayList<Pet>();
            for (Pet petListPetToAttach : owner.getPetList()) {
                petListPetToAttach = em.getReference(petListPetToAttach.getClass(), petListPetToAttach.getPetId());
                attachedPetList.add(petListPetToAttach);
            }
            owner.setPetList(attachedPetList);
            em.persist(owner);
            if (perId != null) {
                perId.getOwnerList().add(owner);
                perId = em.merge(perId);
            }
            for (Pet petListPet : owner.getPetList()) {
                Owner oldOwnIdOfPetListPet = petListPet.getOwnId();
                petListPet.setOwnId(owner);
                petListPet = em.merge(petListPet);
                if (oldOwnIdOfPetListPet != null) {
                    oldOwnIdOfPetListPet.getPetList().remove(petListPet);
                    oldOwnIdOfPetListPet = em.merge(oldOwnIdOfPetListPet);
                }
            }
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Owner owner) throws IllegalOrphanException, NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Owner persistentOwner = em.find(Owner.class, owner.getOwnId());
            Person perIdOld = persistentOwner.getPerId();
            Person perIdNew = owner.getPerId();
            List<Pet> petListOld = persistentOwner.getPetList();
            List<Pet> petListNew = owner.getPetList();
            List<String> illegalOrphanMessages = null;
            for (Pet petListOldPet : petListOld) {
                if (!petListNew.contains(petListOldPet)) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain Pet " + petListOldPet + " since its ownId field is not nullable.");
                }
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            if (perIdNew != null) {
                perIdNew = em.getReference(perIdNew.getClass(), perIdNew.getPerId());
                owner.setPerId(perIdNew);
            }
            List<Pet> attachedPetListNew = new ArrayList<Pet>();
            for (Pet petListNewPetToAttach : petListNew) {
                petListNewPetToAttach = em.getReference(petListNewPetToAttach.getClass(), petListNewPetToAttach.getPetId());
                attachedPetListNew.add(petListNewPetToAttach);
            }
            petListNew = attachedPetListNew;
            owner.setPetList(petListNew);
            owner = em.merge(owner);
            if (perIdOld != null && !perIdOld.equals(perIdNew)) {
                perIdOld.getOwnerList().remove(owner);
                perIdOld = em.merge(perIdOld);
            }
            if (perIdNew != null && !perIdNew.equals(perIdOld)) {
                perIdNew.getOwnerList().add(owner);
                perIdNew = em.merge(perIdNew);
            }
            for (Pet petListNewPet : petListNew) {
                if (!petListOld.contains(petListNewPet)) {
                    Owner oldOwnIdOfPetListNewPet = petListNewPet.getOwnId();
                    petListNewPet.setOwnId(owner);
                    petListNewPet = em.merge(petListNewPet);
                    if (oldOwnIdOfPetListNewPet != null && !oldOwnIdOfPetListNewPet.equals(owner)) {
                        oldOwnIdOfPetListNewPet.getPetList().remove(petListNewPet);
                        oldOwnIdOfPetListNewPet = em.merge(oldOwnIdOfPetListNewPet);
                    }
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Long id = owner.getOwnId();
                if (findOwner(id) == null) {
                    throw new NonexistentEntityException("The owner with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Long id) throws IllegalOrphanException, NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Owner owner;
            try {
                owner = em.getReference(Owner.class, id);
                owner.getOwnId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The owner with id " + id + " no longer exists.", enfe);
            }
            List<String> illegalOrphanMessages = null;
            List<Pet> petListOrphanCheck = owner.getPetList();
            for (Pet petListOrphanCheckPet : petListOrphanCheck) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This Owner (" + owner + ") cannot be destroyed since the Pet " + petListOrphanCheckPet + " in its petList field has a non-nullable ownId field.");
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            Person perId = owner.getPerId();
            if (perId != null) {
                perId.getOwnerList().remove(owner);
                perId = em.merge(perId);
            }
            em.remove(owner);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Owner> findOwnerEntities() {
        return findOwnerEntities(true, -1, -1);
    }

    public List<Owner> findOwnerEntities(int maxResults, int firstResult) {
        return findOwnerEntities(false, maxResults, firstResult);
    }

    private List<Owner> findOwnerEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Owner.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Owner findOwner(Long id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Owner.class, id);
        } finally {
            em.close();
        }
    }

    public int getOwnerCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Owner> rt = cq.from(Owner.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
